<script setup>
import { ref, onMounted } from 'vue'
import TaskAssignDialog from './TaskAssignDialog.vue'
import { ElImageViewer } from 'element-plus'
import DailyDetailDialog from './DailyDetailDialog.vue'

import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  tasks: {
    type: Array,
    default: () => []
  },
  userRole: {
    type: String,
    default: 'user'
  }
})

const emit = defineEmits(['updateTask', 'assignTask', 'deleteTask', 'search'])

// 搜索条件
const searchForm = ref({
  state: '',
  keyword: '',
  startTime: '',
  endTime: '',
  responsibleUserIds: [],
  currentPage: 1,
  pageSize: 10
})

// 分配任务对话框
const showAssignDialog = ref(false)
const currentTask = ref(null)
const selectedAssignees = ref([])

// 弹窗控制
const dialogVisible = ref(false)

// 媒体查看控制
const showImageViewer = ref(false)
const showVideoDialog = ref(false)
const currentImage = ref('')
const currentVideo = ref('')

// Daily 详情对话框控制
const showDailyDialog = ref(false)
const currentDailyId = ref(null)

// 添加这两个响应式变量（放在其他 ref 变量定义的地方）
const dailyDetailVisible = ref(false)
const dailyData = ref([])
const responsibleOptions = ref([])

// 修改状态选项为对象格式
const stateOptions = ref([
  { value: 1, label: '待处理' },
  { value: 2, label: '进行中' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已关闭' }
])

// 获取状态类型（用于时间轴节点的颜色）
const getStateType = (state) => {
  switch (state) {
    case 2: return 'primary'   // 进行中
    case 3: return 'success'   // 已完成
    case 4: return 'info'      // 已关闭
    default: return 'warning'  // 其他状态
  }
}

// 获取状态文本
const getStateText = (state) => {
  switch (state) {
    case 2: return '进行中'
    case 3: return '已完成'
    case 4: return '已关闭'
    default: return '待处理'
  }
}

// 获取状态图标
const getStateIcon = (state) => {
  switch (state) {
    case 2: return 'Loading'    // 进行中
    case 3: return 'Select'     // 已完成
    case 4: return 'CircleClose' // 已关闭
    default: return 'More'      // 其他状态
  }
}

const fetchResponsibleOptions = async () => {
  try {
    const response = await axios.get('/user/queryAll')
    if (response.data.code === 1) {
      responsibleOptions.value = response.data.data
    }
  } catch (error) {
    console.error('获取责任人列表失败:', error)
  }
}

onMounted(() => {
  fetchResponsibleOptions()
})

// 打开分配任务对话框
const openAssignDialog = (task) => {
  currentTask.value = task
  selectedAssignees.value = []
  showAssignDialog.value = true
}

// 处理任务分配
const handleAssign = () => {

  
  emit('assignTask', {
    taskId: currentTask.value.id,
    assignees: selectedAssignees.value
  })
  
  showAssignDialog.value = false
}

// 处理状态更新
const handleStatusUpdate = (task, newStatus) => {
  emit('updateTask', {
    ...task,
    status: newStatus
  })
}

// 处理搜索
const handleSearch = () => {
  emit('search', {
    keyword: searchForm.value.keyword,
    state: searchForm.value.state,
    startTime: searchForm.value.startTime,
    endTime: searchForm.value.endTime,
    responsibleUserIds: searchForm.value.responsibleUserIds
  })
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    state: '',
    keyword: '',
    startTime: '',
    endTime: '',
    responsibleUserIds: []
  }
  handleSearch()
}

// 处理编辑按钮点击
const handleEdit = (task) => {
  currentTask.value = task
  dialogVisible.value = true
}

// 处理编辑完成
const handleEditComplete = () => {
  emit('updateTask')  // 通知父组件刷新任务列表
}

// 处理 Daily 详情按钮点击
const handleShow = async (taskId) => {
  try {
    const response = await axios.get(`/daily/getDailyByTaskId/${taskId}`)
    if (response.data.code === 1) {
      dailyData.value = response.data.data
      dailyDetailVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取问题反馈详情失败')
    }
  } catch (error) {
    console.error('获取问题反馈详情失败:', error)
    ElMessage.error('获取问题反馈详情失败')
  }
}

// 处理内容中的媒体标签
const processContent = (content) => {
  if (!content) return ''
  
  // 为图片和视频添加自定义类名和数据属性
  return content.replace(
    /<img.*?src="(.*?)".*?>/g, 
    '<img class="content-image" data-type="image" src="$1" style="cursor: pointer;">'
  ).replace(
    /<video.*?src="(.*?)".*?>/g,
    '<video class="content-video" data-type="video" src="$1" style="cursor: pointer;">'
  )
}

// 处理媒体点击
const handleMediaClick = (event) => {
  const target = event.target
  if (target.classList.contains('content-image')) {
    currentImage.value = target.src
    showImageViewer.value = true
  } else if (target.classList.contains('content-video')) {
    currentVideo.value = target.src
    showVideoDialog.value = true
  }
}

// 处理关闭视频
const handleCloseVideo = () => {
  const videoPlayer = document.querySelector('.video-player')
  if (videoPlayer) {
    videoPlayer.pause()
  }
  showVideoDialog.value = false
  currentVideo.value = ''
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return time.split('.')[0]  // 用分割的方式去掉 .0
}
const isAdmin = localStorage.getItem('isAdmin') === '1'
const userId = Number(localStorage.getItem('userId'))
</script>

<template>
  <div class="task-list-container">
    <!-- 搜索表单 -->
    <div class="search-container">
      <div class="search-form">
        <div class="form-group">
          <div class="form-item">
            <label>状态：</label>
            <select v-model="searchForm.state" class="form-control">
              <option value="">全部</option>
              <option v-for="option in stateOptions" :key="option.label" :value="option.value">
                {{ option.label }}
              </option>
            </select>
          </div>
          <div class="form-item">
            <label>关键字：</label>
            <input 
              type="text" 
              v-model="searchForm.keyword" 
              placeholder="搜索标题和内容"
              class="form-control"
            >
          </div>
          <div class="form-item">
            <label>责任人：</label>
            <el-select
              v-model="searchForm.responsibleUserIds"
              multiple
              filterable
              collapse-tags
              placeholder="选择责任人"
              clearable
            >
              <el-option
                v-for="user in responsibleOptions"
                :key="user.id"
                :label="user.realname"
                :value="user.id"
              />
            </el-select>
          </div>
        </div>

        <div class="form-group">
          <div class="form-item">
            <label>开始时间：</label>
            <input 
              type="date" 
              v-model="searchForm.startTime"
              class="form-control"
            >
          </div>
          <div class="form-item">
            <label>结束时间：</label>
            <input 
              type="date" 
              v-model="searchForm.endTime"
              class="form-control"
            >
          </div>
        </div>
        <div class="form-group">
          <div class="form-item">
            <label class="invisible">操作</label>
            <div class="button-group">
              <button @click="handleSearch" class="btn btn-primary">搜索</button>
              <button @click="handleReset" class="btn btn-default">重置</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-list">
      <div v-for="task in tasks" :key="task.id" class="task-item">
        <div class="task-header">
          <h3>{{ task.title }}</h3>
          <div class="status-tags">
            <span :class="['status-tag', getStateText(task.state)]">
              {{ getStateText(task.state) }}
            </span>
          </div>
        </div>
        
        <div class="task-info">
          <div class="info-row">
            <span>发布人：{{ task.publishUser.realname }}</span>
            <span>发布时间：{{ formatTime(task.publishTime) }}</span>
          </div>
          <div class="info-row">
            <span>负责人：{{ task.responsibleUser.realname }}</span>
            <span>预计时间：{{ formatTime(task.estimatedTime)}}</span>
          </div>
        </div>

        <div class="task-description">
          <div v-html="processContent(task.description)" @click="handleMediaClick"></div>
        </div>
        
        <!-- 添加任务状态历史时间轴 -->
        <div class="task-history">
          <h4>任务的一生</h4>
          <el-timeline>
            <!-- 起始节点 -->
            <el-timeline-item
              type="primary"
              size="large"
              icon="Pointer"
              timestamp="开始"
            >
              <h5>
                任务创建
                <template v-if="task.responsibleUser">
                  <span class="arrow">→</span>
                  <span class="operator">责任人：{{ task.responsibleUser.realname }}</span>
                </template>
              </h5>
            </el-timeline-item>
            
            <!-- 中间状态变更节点 -->
            <el-timeline-item
              v-for="(history, index) in task.taskStateHistoryList"
              :key="index"
              :type="getStateType(history.state)"
              :timestamp="history.createdTime"
            >
              <div class="history-item">
                <span class="operator">{{ history.user.realname }}操作任务状态：</span>
                <span class="arrow">→</span>
                <span class="state">{{ getStateText(history.state) }}</span>
                <div class="reason" v-if="history.stateReason" @click="handleMediaClick">
                  原因：<span v-html="processContent(history.stateReason)"></span>
                </div>
              </div>
            </el-timeline-item>
            
            <!-- 当前状态节点 -->
            <el-timeline-item
              :type="getStateType(task.state)"
              size="large"
              :icon="getStateIcon(task.state)"
            >
              <h5>当前状态：{{ getStateText(task.state) }}</h5>
            </el-timeline-item>
          </el-timeline>
        </div>
        
        <div class="task-footer">
          
          <div class="actions">  
            <button class="action-btn assign" @click="handleShow(task.id)">问题详情</button>          
            <button class="action-btn edit" @click="handleEdit(task)" v-if="(isAdmin || userId === task.publishUserId || userId === task.responsibleUserId)">编辑</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加任务修改弹窗 -->
    <TaskAssignDialog
      v-model:visible="dialogVisible"
      :task-data="currentTask"
      :is-edit="true"
      @submit="handleEditComplete"
      @refresh="handleSearch" 
    />

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="[currentImage]"
      @close="showImageViewer = false"
    />

    <!-- 视频播放器 -->
    <el-dialog
      v-model="showVideoDialog"
      title="视频播放"
      width="80%"
      :before-close="handleCloseVideo"
    >
      <video
        v-if="currentVideo"
        ref="videoPlayer"
        class="video-player"
        controls
        :src="currentVideo"
      >
        您的浏览器不支持视频播放
      </video>
    </el-dialog>
    
    <!-- Daily 详情对话框 -->
    <DailyDetailDialog
      v-model:visible="dailyDetailVisible"
      :daily-list="dailyData"
    />
  </div>
</template>

<style scoped>
.task-list-container {
  padding: 1rem;
}

.search-container {
  width: 96%;
  margin: 20px auto;
  padding: 24px;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12);
  border-radius: 8px;
}

.search-form {
  width: 100%;
  box-sizing: border-box;
}
.actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;  /* 靠右对齐 */
  margin-left: auto;  /* 推到最右边 */
}

.action-btn {
  padding: 0.25rem 0.75rem;
  border: 1px solid #DFE1E6;
  background-color: white;
  border-radius: 3px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.2s;
}

.action-btn.assign {
  background-color: #fff;
  color: #409EFF;
  border: 1px solid #409EFF;
}

.action-btn.assign:hover {
  background-color: #ecf5ff;
  color: #409EFF;
  border-color: #409EFF;
}

.action-btn.edit {
  color: #67C23A;
  border: 1px solid #67C23A;
}

.action-btn.edit:hover {
  background-color: #f0f9eb;
  border-color: #67C23A;
  color: #67C23A;
}

.action-btn.delete {
  color: #F56C6C;
  border: 1px solid #F56C6C;
}

.action-btn.delete:hover {
  background-color: #fef0f0;
  border-color: #F56C6C;
  color: #F56C6C;
}
.form-group {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: calc(33.33% - 11px); /* 考虑到间隔的 16px */
  min-width: 0; /* 防止内容溢出 */
}

.form-item label {
  font-size: 14px;  /* 设置标签文字大小 */
}

.invisible {
  visibility: hidden;
}

.form-item input,
.form-item select {
  height: 40px;  /* 调整输入框和选择框的高度 */
  font-size: 14px;  /* 设置文字大小 */
  padding: 0 15px;  /* 调整内边距 */
}
:deep(.form-item .el-select) {
  width: 100%;
}

.form-control {
  width: 100%;
  height: 32px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-control:focus {
  border-color: #409eff;
  outline: none;
}

.button-group {
  display: flex;
  gap: 8px;
  height: 32px;
  justify-content: flex-end; /* 按钮靠右对齐 */
}

.btn {
  padding: 0 16px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #409eff;
  border: 1px solid #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.btn-default {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.btn-default:hover {
  color: #409eff;
  border-color: #409eff;
}

@media (max-width: 768px) {
  .form-group {
    flex-direction: column;
  }
}

.tasks-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.task-item {
  background-color: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.task-header h3 {
  margin: 0;
  font-size: 1.1rem;
  color: #333;
}

.status-tags {
  display: flex;
  align-items: center;
}

.status-tag {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
}

.status-tag.待处理 { background-color: #ffd666; }
.status-tag.进行中 { background-color: #40a9ff; color: white; }
.status-tag.已完成 { background-color: #52c41a; color: white; }
.status-tag.已关闭 { background-color: #d9d9d9; }

.task-info {
  margin-bottom: 1rem;
}

.info-row {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
}

.task-description {
  color: #444;
  font-size: 0.9rem;
  line-height: 1.5;
  margin-bottom: 1rem;
}

/* 富文本内容样式 */
.task-description :deep(img) {
  max-width: 200px;  /* 默认显示较小的尺寸 */
  height: auto;
  cursor: pointer;
  transition: transform 0.2s;
  border-radius: 4px;  /* 添加圆角 */
  margin: 4px;  /* 添加间距 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);  /* 添加轻微阴影 */
}

.task-description :deep(img:hover) {
  transform: scale(1.05);  /* 悬停时轻微放大 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);  /* 悬停时增强阴影 */
}

.task-description :deep(video) {
  max-width: 100%;
  height: auto;
  cursor: pointer;
  border-radius: 4px;
}

.task-description :deep(p) {
  margin: 0.5em 0;
}

.task-description :deep(ul),
.task-description :deep(ol) {
  padding-left: 2em;
  margin: 0.5em 0;
}

.task-description :deep(blockquote) {
  margin: 0.5em 0;
  padding: 0.5em 1em;
  border-left: 4px solid #ddd;
  background: #f9f9f9;
}

.task-description :deep(pre) {
  background: #f6f8fa;
  padding: 1em;
  border-radius: 4px;
  overflow-x: auto;
}

.task-description :deep(code) {
  background: #f6f8fa;
  padding: 0.2em 0.4em;
  border-radius: 3px;
  font-family: monospace;
}

.task-description :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 0.5em 0;
}

.task-description :deep(th),
.task-description :deep(td) {
  border: 1px solid #ddd;
  padding: 0.5em;
}

.task-description :deep(a) {
  color: #0366d6;
  text-decoration: none;
}

.task-description :deep(a:hover) {
  text-decoration: underline;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 1rem;
  border-top: 1px solid #eee;
}

.assign-btn {
  padding: 0.25rem 0.75rem;
  background-color: #0052cc;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.assign-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.checkbox-group {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

/* 视频播放器样式 */
.video-player {
  width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

/* 图片查看器中的图片样式 */
:deep(.el-image-viewer__img) {
  max-width: 90vw;  /* 查看器中的图片最大宽度 */
  max-height: 90vh;  /* 查看器中的图片最大高度 */
  object-fit: contain;  /* 保持图片比例 */
}

/* 图片查看器样式优化 */
:deep(.el-image-viewer__wrapper) {
  background-color: rgba(0, 0, 0, 0.9);  /* 更深的背景色 */
}

:deep(.el-image-viewer__actions) {
  opacity: 0.9;  /* 控制按钮稍微透明 */
}

:deep(.el-image-viewer__close) {
  color: #fff;
  font-size: 24px;  /* 更大的关闭按钮 */
  opacity: 0.8;
}

:deep(.el-image-viewer__close:hover) {
  opacity: 1;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding-right: 0;
}

:deep(.el-dialog__body) {
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000;
}

:deep(.el-select) {
  width: 100px;
}

:deep(.el-input__wrapper) {
  background-color: transparent;
}

/* 按钮样式调整 */
.search-btn,
.reset-btn {
  height: 40px;  /* 调整按钮高度 */
  font-size: 14px;  /* 设置按钮文字大小 */
  padding: 0 20px;  /* 调整按钮内边距 */
}

.task-history {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.task-history h4 {
  margin-bottom: 16px;
  color: #333;
  font-weight: 500;
}

.history-item {
  padding: 8px 0;
}

.history-item .operator {
  font-weight: 500;
  color: #409EFF;
}

.history-item .arrow {
  margin: 0 8px;
  color: #909399;
}

.history-item .state {
  font-weight: 500;
}

.history-item .reason {
  margin-top: 8px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.history-item .reason :deep(a) {
  color: #409EFF;
  text-decoration: none;
}

.history-item .reason :deep(a:hover) {
  color: #66b1ff;
  text-decoration: underline;
}

.history-item .reason :deep(img) {
  max-width: 100%;
  height: auto;
  cursor: pointer;
  margin: 8px 0;
}

.history-item .reason :deep(video) {
  max-width: 100%;
  height: auto;
  margin: 8px 0;
}

:deep(.el-timeline-item__node--large) {
  width: 16px;
  height: 16px;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 13px;
}
</style>
